package net.mfjassociates.financial.server.rest;

import static net.mfjassociates.financial.server.domain.DocumentId.getInstance;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

import com.sun.jersey.api.NotFoundException;

@Path("/randomset")
public class RandomizedSetResource {
	private static final int MAX_SET_SIZE=500;
	// Application integration
	@GET
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	@Path("{start}/{end}")
	public RandomList getIntegers(@PathParam("start") Integer start,
			@PathParam("end") Integer end) {
		if (end<start) { // assume the order was inversed
			int bucket=end;
			end=start;
			start=bucket;
		}
		
		if ((1+end-start)>MAX_SET_SIZE) {
			throw new NotFoundException("This set is not found because it is too large ("+(1+end-start)+" elements)");
		}
		
		List<Integer> rset = new ArrayList<Integer>(end - start + 1);
		for (int i = start; i <= end; i++) {
			rset.add(i);
		}
		Collections.shuffle(rset);
		return new RandomizedSetResource.RandomList(rset);
	}

	@XmlRootElement
	static class RandomList {
		
		@XmlAttribute String id=getInstance().getId();
		public List<Integer> rset;
		
		public RandomList() {			
		}
		
		public RandomList(List<Integer> rset) {
			this();
			this.rset = rset;
		}

	}
}

